import httplib, urllib, time, sys, threading
from threading import Thread, Condition

SERVER = "10.1.1.10:7775"

class Client(Thread):

    def __init__(self, data):
        Thread.__init__(self)
        self.data = data

        self.conn = httplib.HTTPConnection(SERVER)
        
    def ReadFile(self, filenum):
    
        headers = {"Content-type": "text/plain", "Connection": "Keep-Alive"}
        filename = "/index%d.html" % filenum
        self.conn.request("GET", filename, "", headers)
        response = self.conn.getresponse()
        sum = int(response.getheader("Content-Length"))
        dummy_data = response.read()
        return sum
    
    def run(self):
        bytes = 0
        requests = 0
        start_time = time.time()
        end_time = start_time
        
        while (end_time - start_time < 20):
            for i in range(0,15):
                bytes += self.ReadFile(i)
                end_time = time.time()
                requests += 1
        self.conn.close()
        self.data.updateRateTotal(bytes / (end_time - start_time), requests / (end_time - start_time))
        
class Data:

    def __init__(self, total_clients):
        self.rate_lock = Condition()
        self.rate = 0
        self.requests = 0
        self.participants = 0
        self.total = total_clients

    def updateRateTotal(self, new_rate, requests):
        self.rate_lock.acquire()
        self.rate += new_rate
        self.requests += requests
        #print "%.02f:%.02f:%.02f" % ((new_rate * 8 / 1024 / 1024), (self.rate * 8 / 1024 / 1024), self.requests)
        self.participants +=1
        self.rate_lock.notify()
        self.rate_lock.release()

    def waitForClients(self):
        self.rate_lock.acquire()
        while (self.participants < self.total):
            self.rate_lock.wait()
        print "%.02f Mb/s" % (self.rate * 8 / 1024 / 1024)
        print "%.02f KReq/s" % (self.requests / 1000)
        self.rate_lock.release()
        
    
                    

if __name__ == '__main__':

    data = Data(int(sys.argv[1]))

    for i in range(0,int(sys.argv[1])):
        client = Client(data)
        client.start()

    data.waitForClients()
        



    
